$(function() {
	console.log(window.innerHeight)
	
	mapheight=window.innerHeight-250+'px'
	
	$('#map').css('height',mapheight)
	var car_num = 100;
	var stringEl = $('.str3').liMarquee();
	var isrefresh=1;
	var bdreDate = new Date();
	var page=1;
	var qd=[118.57, 24.82];
	var mouseTool;//拉框
	var imgarr=['{$static_dir}/assets/img/car-blue.png'
				,'{$static_dir}/assets/img/car-greed.png'
				,'{$static_dir}/assets/img/car-greed.png'
				,'{$static_dir}/assets/img/car-gray.png'
				,'{$static_dir}/assets/img/car-red.png'
				,'{$static_dir}/assets/img/car-greed.png'
				,'{$static_dir}/assets/img/car-gray.png'
				,'{$static_dir}/assets/img/car-blue.png'
				,'{$static_dir}/assets/img/car-greed.png'
				,'{$static_dir}/assets/img/car-gray.png'
				,'{$static_dir}/assets/img/car-greed.png'
				,'{$static_dir}/assets/img/car-red.png']  //兴趣点图标
	var origin = {
		car: [],     //车辆
		order: [],   //订单
		interest:[]  //兴趣点
	};
	var cluster, markers = [];  //点聚合
	var fence=[]; //电子围栏
	var datepath=[];
	
	//地图
	map = new AMap.Map('map', {
		resizeEnable: true,
		zoom: 10,
		center: qd
	});
	AMapUI.loadUI(['control/BasicControl'],function(BasicControl) {
	  	var layerCtrl1 = new BasicControl.LayerSwitcher({
	        position: 'tr'
	    });
	map.setStatus({ layers: layerCtrl1.getEnabledLayers()});
	   map.addControl(layerCtrl1);
	})
	var trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10
    });
    trafficLayer.setMap(map);
      trafficLayer.hide();
	
	var id, orderid, ordercont;
	//搜索
//	mapsearch(map)

	//工具
	tool(map,trafficLayer)
	//右击
    rightclick(map,imgarr,origin,fence)

	//租车公司选择
	$('.car_rental').on('click', function() {
		choosecar("{:url('rent/index',['op'=>'search'])}")
	});
	$('.dayin').on('click',function(){
		$('header').css('display','none')
		$('.tpl-skiner').css('display','none')
		$('.left-sidebar').css('display','none')
		$('form').parent().css('display','none')
		$('.carlist').css('display','none')
		$('.orderlist').css('display','none')
		$('.tpl-content-wrapper').css('margin',0)
		$('.am-breadcrumb').css('display','none')
		$('.car_date').css('display','none')
		$('.button-group').css('display','none')
		
		$('#map').height('700px')
		$('#map').width('1200px')
		setTimeout(function() {
		window.print()
		},500)
		if(tata=document.execCommand("print")){
			window.history.go(0)
		}
	})
	var infoWindow;
	//构造路线导航类
	var driving = new AMap.Driving({
		map: map,
		//		panel: "panel"
	});
	
	$('.page').html(page)
	AMapUI.loadUI(['overlay/SimpleMarker', 'overlay/SimpleInfoWindow', 'misc/PathSimplifier'], function(SimpleMarker, SimpleInfoWindow, PathSimplifier) {
		//节点颜色
		
		//轨迹
		var pathSimplifierIns = new PathSimplifier({
			zIndex: 100,
			map: map, //所属的地图实例
			getPath: function(pathData, pathIndex) {
				//返回轨迹数据中的节点坐标信息，[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
				return pathData.path;
			},
			getHoverTitle: function(pathData, pathIndex, pointIndex) {
				//返回鼠标悬停时显示的信息
				if(pointIndex >= 0) {
					//鼠标悬停在某个轨迹节点上
					return pathData.name + '，点:' + pointIndex + '/' + pathData.path.length;
				}
				//鼠标悬停在节点之间的连线上
				return pathData.name + '，点数量' + pathData.path.length;
			},
			renderOptions: {
				//轨迹线的样式
				pathLineStyle: {
					strokeStyle: 'red',
					lineWidth: 6,
					dirArrowStyle: true
				}
			}
		});
		//信息窗口
		
		
		bdreDate = new Date()
		var bdreDateshow=bdreDate.getFullYear()+'-'+(bdreDate.getMonth()+1)+'-'+bdreDate.getDate()+' '+bdreDate.getHours()+':'+bdreDate.getMinutes()+':'+bdreDate.getSeconds();
		$('.retime').html('('+bdreDateshow+')')
		setInterval(function() {
			$('.retime').html('('+bdreDateshow+')')
			if(isrefresh){
				bdreDate = new Date();
				bdreDateshow=bdreDate.getFullYear()+'-'+(bdreDate.getMonth()+1)+'-'+bdreDate.getDate()+' '+bdreDate.getHours()+':'+bdreDate.getMinutes()+':'+bdreDate.getSeconds();
				$('.retime').html(bdreDateshow)
				$('.carlist ul').html("")
				$('.orderlist ul').html("")
				pathSimplifierIns.hide();
				map.clearMap();
				{if $Think.get.number}
				ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
				{else/}
				ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
				{/if}
				}
			}, 600000)
		{if $Think.get.number}
		ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
		{else/}
		ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
		{/if}
		
		
		
		$('.backcar').on('click', function() {
			$('.daochu').css('display','none')
			isrefresh=1
			bdreDate = new Date()
			var bdreDateshow=bdreDate.getFullYear()+'-'+(bdreDate.getMonth()+1)+'-'+bdreDate.getDate()+' '+bdreDate.getHours()+':'+bdreDate.getMinutes()+':'+bdreDate.getSeconds();
		
			$('.retime').html('('+bdreDateshow+')')
			$('.carlist ul').html("")
			$('.orderlist ul').html("")
			map.setZoomAndCenter(10, qd);
			pathSimplifierIns.hide();
			map.clearMap();
			{if $Think.get.number}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
			{else/}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
			{/if}
		})
		$('.car_num').on('change', function() {
			isrefresh=1
			bdreDate = new Date()
			var bdreDateshow=bdreDate.getFullYear()+'-'+(bdreDate.getMonth()+1)+'-'+bdreDate.getDate()+' '+bdreDate.getHours()+':'+bdreDate.getMinutes()+':'+bdreDate.getSeconds();
			
			$('.retime').html('('+bdreDateshow+')')
			$('.carlist ul').html("")
			$('.orderlist ul').html("")
			map.setZoomAndCenter(10, qd);
			pathSimplifierIns.hide();
			map.clearMap();
			car_num = $(this).val();
			{if $Think.get.number}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
			{else/}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
			{/if}
		})
	})

	//请求数据car
	function ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, infoWindow{if $Think.get.number},number{/if},PathSimplifier,page) {
		var carload = layer.load(0, {
			shade:  [0.3,'#fff']
		});
		$('.carlist').css('display', 'block');
		$('.orderlist').css('display', 'none');
		$('.car_date').css('display', 'none');
		$.ajax({
			type: "post",
			url: "{:url('/adminapi/beidou/cars')}",
			data: {
				pagesize: car_num
				{if $Think.get.number},number:number{/if}
				{if $Think.get.car_rental_id},car_rental_id:{$Think.get.car_rental_id}{/if}
			},
			success: function(res) {
				console.log(res)
				layer.close(carload);
				if(res.code == 1) {
					
					{if $Think.get.car_state}
					for(var stateidx=0;stateidx<res.data.length;stateidx++){
						if(res.data[stateidx].state=={$Think.get.car_state}){
							origin.car.push(res.data[stateidx])
						}
					}
					{else/}
					if(typeof res == 'string') {
						origin.car = JSON.parse(res).data;
					} else {
						origin.car = res.data;
					};
					{/if}
					$('.carnum').html('(共'+origin.car.length+'辆)')
				//				}
				
				for(var caridx = 0; caridx < origin.car.length; caridx++) {
					
					
					carlistshow(caridx, origin);
					
					if(origin.car[caridx].loc[0]){
					addcarMarker(origin, caridx, SimpleMarker);
					origin.car[caridx].point.on('mouseover', function() {
						openmessage(map, this, SimpleInfoWindow, infoWindow, 1);
						
					})
					origin.car[caridx].point.on('mouseout',function(){
						closemessage(map, this, SimpleInfoWindow, infoWindow)
					})
					origin.car[caridx].point.on('click', function() {
						
						isrefresh=0
						var carthat = this;
						clear(origin, this, map,cluster,SimpleMarker);

						openmessage(map, this, SimpleInfoWindow, infoWindow, 1);
						//循环遍历获取车辆id
						for(var index in carthat) {
							for(var index1 in carthat[index]) {
								if(index1 == "cont") {
									id = carthat[index].cont.carid;
									loc=carthat[index].cont.loc
									number=carthat[index].cont.num
								};
							};
						};
						map.setZoomAndCenter(14, loc);
						
						ordertitle(number)
						
						ajaxorder(origin, id, this, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
						//上一页
						$('.previous').on('click',function(){
							pathSimplifierIns.hide();
							$('.orderlist ul').html('');
							if(page<=1){
							}else{
								clearorder(origin, map) 
								page-=1
								$('.page').html(page)
							}
							ajaxorder(origin, id, carthat, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
						});
						//下一页
						$('.next').on('click',function(){
							pathSimplifierIns.hide();
							$('.orderlist ul').html('');
							clearorder(origin, map) 
							page+=1
							$('.page').html(page)
							ajaxorder(origin, id, carthat, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
						});
					})
					}else{
					}
				};
				cluster=addCluster(2,origin,cluster, markers)
				console.log(cluster)
				

				ulheight();
				$('.carlist ul li').on('click', function() {
					isrefresh=0;
					var carlistidx = $(this).index();
					if(origin.car[carlistidx].point){
					var nod = origin.car[carlistidx].point;
					clear(origin, nod, map, cluster,SimpleMarker);

					openmessage(map, nod, SimpleInfoWindow, infoWindow, 1);
					for(var index in nod) {
						for(var index1 in nod[index]) {
							if(index1 == "cont") {
								id = nod[index].cont.carid;
							};
						};
					};
					map.setZoomAndCenter(11, origin.car[carlistidx].loc);
					ordertitle(origin.car[carlistidx].number)
					ajaxorder(origin, id, nod, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
					$('.previous').on('click',function(){
						pathSimplifierIns.hide();
						$('.orderlist ul').html('');
						clear(origin, nod, map, cluster,SimpleMarker);

						if(page<=1){
						}else{
							clearorder(origin, map) 
							page-=1
							$('.page').html(page)
						}
						ajaxorder(origin, id, nod, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
					});
					$('.next').on('click',function(){
						pathSimplifierIns.hide();
						$('.orderlist ul').html('');
						clearorder(origin, map) 
						page+=1
						$('.page').html(page)
						ajaxorder(origin, id, nod, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
					});
					}else{
						Err('暂无信息')
					}
				})
				
				}
			},
			error:function(){
				layer.close(carload);
				Err('请求失败')
			}
		})
	}

	//请求数据order
	function ajaxorder(origin, id, car, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page) {
		
		var orderload = layer.load(0, {
			shade:  [0.3,'#fff']
		});
		$('.carlist').css('display', 'none');
		$('.orderlist').css('display', 'block');
		$('.car_date').css('display', 'block');
		$('.car_date button').on('click',function(){
			console.log(11)
			if($('.car_date .stardate').val()){
				console.log('stardate');
				if($('.car_date .enddate').val()){
					console.log('enddate');
					var dat1 = $('.car_date .stardate').val()
					var dat2 = $('.car_date .enddate').val()
					dat1 = new Date(dat1)
					dat2 = new Date(dat2)
					if(dat2>dat1){
						console.log(dat2-dat1)
						if((dat2-dat1)>(10*24*3600*1000)){
							Err('只能获取10天内的路径')
						}else{
							
							var data1=$('.car_date .stardate').val().replace('T', " ")
							var data2=$('.car_date .enddate').val().replace('T', " ")
							console.log(data1)
							console.log($('.car_date .stardate').val().indexOf("T"))
							ajaxdatepath(map, data1,data2,$('.date_number').val(),SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier)
							$('.daochu').unbind()
							$('.daochu').on('click',function(){
								window.open("http://new.jjcxfw.com/adminapi/beidou/getDate?start="+data1+"&end="+data2+"&number="+$('.date_number').val()+"&act=export")
							})
						}
					}else{
						Err('开始时间要在结束时间之前')
					}
				
				}else{
					Msg('请输入结束时间')
				}
			}else{
				Msg('请输入开始时间')
			}
			
//			if(datejudge($('.car_date .stardate').val(),$('.car_date .enddata').val()))
//			if($('.car_date input[type=date]').val()==''){
//				Err('时间不能为空')
//			}else{
//				ajaxdatepath(map, $('.car_date .stardate').val(),$('.car_date .enddate').val(),$('.date_number').val(),SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier)
//			}
		})
		$.ajax({
			type: "post",
			url: "{:url('/adminapi/beidou/orders')}",
			data: {
				id: id,
				page:page,
				pagesize:20,
			},
			success: function(res) {
				console.log(res)
				layer.close(orderload);
				if(res.code == 1) {
					if(typeof res == 'string') {
						origin.order = JSON.parse(res).data;
					} else {
						origin.order = res.data;
					}
					console.log('order')
					console.log(origin)
					for(var orderidx = 0; orderidx < origin.order.length; orderidx++) {
						//加评星
						if(origin.order[orderidx].star){
						orderlistshow(orderidx, origin.order[orderidx].star, origin.order);
						}else{
							orderlistshow(orderidx, 0, origin.order);
						}
						addOrderMarker(orderidx, origin, SimpleMarker);
					};
					orderulheight()
					//点击订单修改路线
					for(var j = 0; j < origin.order.length; j++) {
						origin.order[j].point.on('mouseover', function() {
							openmessage(map, this, SimpleInfoWindow, infoWindow, 2);
						})
						origin.order[j].point.on('mouseout',function(){
								closemessage(map, this, SimpleInfoWindow, infoWindow)
						})
						origin.order[j].point.on('click', function() {
							$('.daochu').css('display','none')
							map.remove(car);
							for(var item in this) {
								for(var item1 in this[item]) {
									if(item1 == 'cont') {
										orderid = this[item][item1].orderid
									};
								};
							};
							openmessage(map, this, SimpleInfoWindow, infoWindow, 2);
							ajaxpath(orderid, pathSimplifierIns, SimpleInfoWindow,infoWindow,PathSimplifier);
						});
					};
					$('.orderlist ul li').on('click', function() {
						$('.daochu').css('display','none')
						var orderlistidx = $(this).index();
						orderid = origin.order[orderlistidx].order_id;
						map.remove(car);
						openmessage(map, origin.order[orderlistidx].point, SimpleInfoWindow, infoWindow, 2);
						ajaxpath(orderid, pathSimplifierIns, SimpleInfoWindow,infoWindow,PathSimplifier);
					})
				};
			},
					error:function(){
						layer.close(carload);
						Err('请求失败')
					}
		})
	}
	
	
	
	
	
	
	//请求该车辆一天的轨迹

	function ajaxdatepath(map,date1,date2,number,SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier){
		console.log(date1)
		console.log(date2)
		$('.daochu').css('display','inline-block')
		var datepathload = layer.load(0, {
			shade:  [0.3,'#fff']
		});
	
		$.ajax({
			type: "post",
			data: {
				start: date1,
				end: date2,
				number: number
			},
			url: "http://new.jjcxfw.com/adminapi/beidou/getDate",
			success: function(res) {
				console.log(res)
				layer.close(datepathload);
				if(res.code==1){
					if(res.data.length>0){
						initPage(PathSimplifier, map, res.data, pathSimplifierIns,1)
					}else{
						Err('今日暂无路径')
					}
				}else{
					Err('请求失败')
				}
			},
			error:function(){
				layer.close(datepathload);
				Err('请求失败')
			}
		})
	}
	//请求数据path
	function ajaxpath(orderid, pathSimplifierIns, SimpleInfoWindow,infoWindow,PathSimplifier) {
		var pathload = layer.load(0, {
			shade:  [0.3,'#fff']
		});
		$.ajax({
			type: "post",
			data: {
				oid: orderid
			},
			url: "{:url('/admin/order/getTrack')}",
			success: function(res) {
				
				layer.close(pathload);
				var allpath = [];
				if(typeof res == 'string') {
					var opath1 = JSON.parse(res).data;
				} else {
					var opath1 = res.data;
				}
				var opath2 = [];
				var opath = [];
				
				if(opath1.length > 1) {
					for(var rankidx = 0; rankidx < opath1.length; rankidx++) {
						opath2.push(opath1[rankidx].time);
					}
					opath2.sort();
					for(var k = 0; k < opath2.length; k++) {
						for(var j = 0; j < opath1.length; j++) {
							if(opath2[k] == opath1[j].time) {
								opath.push(opath1[j]);
							}
						}
					}
					for(var oi = 0; oi < opath.length; oi++) {
						var oarr = [];
						oarr.push(opath[oi].longitude);
						oarr.push(opath[oi].latitude);
						allpath.push(oarr);
					}

					initPage(PathSimplifier, map, allpath, pathSimplifierIns);
				} else {
					Err('暂无轨迹信息');
				}
			},
					error:function(){
						layer.close(carload);
						Err('请求失败')
					}
		})
	}
	
	
	//添加车辆节点
	function addcarMarker(origin, caridx, SimpleMarker) {
		var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');
		var pointimg;
		if(origin.car[caridx].state==1) {
			pointimg='{$static_dir}/assets/img/car-blue.png';
		}else if(origin.car[caridx].state==2){
			pointimg='{$static_dir}/assets/img/car-greed.png';
		}else if(origin.car[caridx].state==3){
			pointimg='{$static_dir}/assets/img/car-gray.png';
		}else if(origin.car[caridx].state==4){
			pointimg='{$static_dir}/assets/img/car-red.png';
		};
		var str = new RegExp('黄', "i");
		if(origin.car[caridx].number.match(str)){
			origin.car[caridx].point = new SimpleMarker({
			//普通文本
			iconStyle: {
				src: pointimg,
				style: {
					width: '15px',
					height: '30px'
				}
			},
			position: origin.car[caridx].loc,
			 label: {
                    content:`<div style='background:yellow;width:100%;height:100%;color:#000;padding:3px;'>${origin.car[caridx].number}<div>`,
                    offset: new AMap.Pixel(-25, 34),
                    style:{
					width:'200px'
					
					}
                },
			cont: {
				carid: origin.car[caridx].car_id,
				driverid: origin.car[caridx].driver_id,
				num: origin.car[caridx].number,
				loc: origin.car[caridx].loc,
				name: origin.car[caridx].name,
				phone: origin.car[caridx].phone,
				work_state: origin.car[caridx].state
			}
		});
		}else{
			origin.car[caridx].point = new SimpleMarker({
			//普通文本
			iconStyle: {
				src: pointimg,
				style: {
					width: '15px',
					height: '30px'
				}
			},
			position: origin.car[caridx].loc,
			 label: {
                    content:`<div style='background:blue;width:100%;height:100%;color:#fff;padding:3px;'>${origin.car[caridx].number}<div>`,
                    offset: new AMap.Pixel(-20, 34)
                },
			cont: {
				carid: origin.car[caridx].car_id,
				driverid: origin.car[caridx].driver_id,
				num: origin.car[caridx].number,
				loc: origin.car[caridx].loc,
				name: origin.car[caridx].name,
				phone: origin.car[caridx].phone,
				work_state: origin.car[caridx].state
			}
		});
		}
		origin.car[caridx].point.setMap(map);
	}
	//添加订单节点
	function addOrderMarker(i, origin, SimpleMarker) {
		var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');
		origin.order[i].path=[];
		origin.order[i].path.push(origin.order[i].from_lon-0);
		origin.order[i].path.push(origin.order[i].from_lat-0);

		
		
		origin.order[i].point = new SimpleMarker({ 
			//普通文本
			iconStyle: iconStyles[2],
			//图标文字
			iconLabel: {
				//A,B,C.....
				innerHTML: i + 1,
				style: {
					color: '#fff'
				}
			}, 
			map: map,
			position: origin.order[i].path,
			path: origin.order[i].path,
			cont: {
				money:origin.order[i].order_money,
				time:origin.order[i].orders_time,
				drivername: origin.order[i].driver_name,
				begin: origin.order[i].departure,
				end: origin.order[i].destination,
				orderid: origin.order[i].order_id
			}
		});
		origin.order[i].point.setMap(map);
	};

	//车辆列表ul高度
function ulheight() {
	
//	var carlistul = $('.carlist-list ul li').height()*5;
	var carlistul=0;
	for(var carlistli = 0; carlistli < $('.carlist-list ul li').length; carlistli++) {
		carlistul += 40;
		
	};
	$('.carlist-list ul').height(carlistul);
	var myScroll = new IScroll('.carlist-list', {
		mouseWheel: true,
		disableMouse: true,
	});
	
}
function orderulheight() {
	
	var orderlistul = 0;
	for(var orderlistli = 0; orderlistli < $('.carlist-list ul li').length; orderlistli++) {
		orderlistul += $('.carlist-list ul li').height()
	};
	$('.carlist-list ul').height(orderlistul);
	var myScroll = new IScroll('.orderlist-list', {
		mouseWheel: true,
		disableMouse: true,
	});
}
//清除地图上得到所有节点
function clearall(origin, map) {
	for(var delcaridx = 0; delcaridx < origin.car.length; delcaridx++) {
		map.remove(origin.car[delcaridx].point);
	};
	for(var delorderidx = 0; delorderidx < origin.order.length; delorderidx++) {
		map.remove(origin.order[delorderidx].point);
	};
	$('.carlist').css('display', 'block');
	$('.orderlist').css('display', 'none');

}
//清除地图上除了点击的节点以外的所有节点
function clear(origin, obj, map,cluster,SimpleMarker) {

	var markers1=[];
	for(var maidx=0;maidx<origin.car.length;maidx++){
    		if(origin.car[maidx].point){
    			markers1.push(origin.car[maidx].point)
    		}
    	}
	console.log()

	if(cluster){
	cluster.clearMarkers( )
	}
	for(var delidx = 0; delidx < origin.car.length; delidx++) {
		if(origin.car[delidx].point){
		if(origin.car[delidx].point === obj) {
			addcarMarker(origin, delidx, SimpleMarker) 
		} else {
//			map.remove(origin.car[delidx].pointtext);
			map.remove(origin.car[delidx].point);
		};
		}
	};
	
	$('.carlist').css('display', 'none');
	$('.orderlist').css('display', 'block');

}
//清除地图上所有订单节点
function clearorder(origin, map) {
	for(var delorderidx = 0; delorderidx < origin.order.length; delorderidx++) {
		map.remove(origin.order[delorderidx].point);
	};
}
//车辆列表
function carlistshow(caridx, obj) {
	var state='';
	if(obj.car[caridx].state){
		if(obj.car[caridx].state==1){
			state='在线-停止'
		}else if(obj.car[caridx].state==2){
			state='在线-行驶'
		}else if(obj.car[caridx].state==3){
			state='离线'
		}else if(obj.car[caridx].state==4){
			state='终端没电'
		}
		
	}else{
		state='终端没电'
	}
	$('.carlist ul').append(`
		<li style="height: 40px;padding: 10px 0;border-top: 1px solid #ccc;cursor: pointer;">
			<div class="am-u-sm-2" style="">
				<div style="border:1px solid #5FB878;margin:0;color:#5FB878;border-radius:50%;width:20px;height:20px;font-size:12px;line-height:20px;text-align:center">${caridx+1}</div>
			</div>
			<div class = "am-u-sm-10 ">
				<div class = "am-u-sm-6  am-text-truncate" style="font-size:12px">${obj.car[caridx].number}</div>
				<div class='am-u-sm-6' style="font-size:12px">${state}</div>
			</div>
			
		</li>`);

}

function ordertitle(number){
	$('.ordertitle').html(number)
	$('.date_number').val(number)
}
//订单列表
function orderlistshow(i, star, obj) {
	var orderstate='';
	if(obj[i].order_state==1){
		orderstate='待审核';
	}else if(obj[i].order_state==3){
		orderstate='已拒绝';
	}else if(obj[i].order_state==4){
		orderstate='待用车';
	}else if(obj[i].order_state==5){
		orderstate='已派车';
	}else if(obj[i].order_state==6){
		orderstate='接驾中';
	}else if(obj[i].order_state==7){
		orderstate='已到达出发地';
	}else if(obj[i].order_state==8){
		orderstate='已到达目的地';
	}else if(obj[i].order_state==9){
		orderstate='待支付';
	}else if(obj[i].order_state==10){
		orderstate='待评价';
	}else if(obj[i].order_state==11){
		orderstate='已完成';
	}else if(obj[i].order_state==12){
		orderstate='已取消';
	}else if(obj[i].order_state==13){
		orderstate='已终止';
	}else if(obj[i].order_state==14){
		orderstate='已取消';
	}
	if(obj[i].complete_time){
		complete_time=obj[i].complete_time
	}else{
		complete_time='-'
	}
	var starimg;
	$('.orderlist ul').append(`
		<li style="height: 60px;padding: 10px 0;border-top: 1px solid #ccc;cursor: pointer;">
			<div class="am-u-sm-2" style="padding:5px;">
				<div style="border:1px solid #5FB878;margin:0;color:#5FB878;border-radius:50%;width:20px;height:20px;font-size:12px;line-height:20px;text-align:center">${i+1}</div>
			</div>
			<div class = "am-u-sm-6 cl-p">
				<div class = "am-u-sm-12 cl-p am-text-truncate" style="font-size:12px">${obj[i].orders_time}</div>
				<div class = "am-u-sm-12 cl-p am-text-truncate" style="font-size:12px">${complete_time}</div>
			</div>
			<div class="am-u-sm-3">
				<div class = "am-u-sm-12 cl-p am-text-truncate" style="font-size:12px;text-align:center">${orderstate}</div>
				<div class = "am-u-sm-12 cl-p am-text-truncate star" style="font-size:12px">
					
				</div>
			</div>
	</li>`);
	//判断星级
	for(var k = 0; k < parseInt(star); k++) {
		$('.star').append(`<img style="width:20%;height:12px" src="{$static_dir}/assets/img/star-on.png"/>`);
	};
	if(star - parseInt(star) > 0) {
		$('.star').append(`<img style="width:20%;height:12px" src="{$static_dir}/assets/img/star-half.png"/>`);
	};
	for(var l = 0; l < 5 - Math.ceil(star); l++) {
		$('.star').append(`<img style="width:20%;height:12px" src="{$static_dir}/assets/img/star-off.png"/>`);
	};

}
//点击图标获取订单信息
function getordercont(obj, ordercont, PathSimplifier, map, pathSimplifierIns) {
	//	pathSimplifierIns.show();
	for(var index in obj) {
		for(var index1 in obj[index]) {
			if(index1 == "cont") {
				idx = index;
				ordercont = obj[index].cont;
				ordercont.path = obj[index].path;
			};
		};
	};

	//	initPage(PathSimplifier, map, ordercont, pathSimplifierIns)
}
//规划路径
function getpath(obj, map, driving, SimpleMarker, SimpleInfoWindow) {
	var arr;
	var content;

	for(var index in obj) {
		for(var index1 in obj[index]) {
			if(index1 == "cont") {
				idx = index;
				arr = obj[index].path;
				content = obj[index].cont;
			};
		};
	};
	var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');

	//设置数据
	driving.search(new AMap.LngLat(arr[0][0], arr[0][1]), new AMap.LngLat(arr[arr.length - 1][0], arr[arr.length - 1][1]));
	map.setZoomAndCenter(13, arr[arr.length - 1]);
};

//轨迹
function initPage(PathSimplifier, map, path, pathSimplifierIns,type) {
if(type){
	//轨迹回放无操作
	console.log(path)
	pathSimplifierIns.show()
	//订单轨迹速度
	var alljourney = 0;
	for(var pidx = 0; pidx < path.length - 1; pidx++) {
		var journey = Math.sqrt(Math.pow((path[pidx][0] - path[pidx + 1][0]), 2) + Math.pow((path[pidx][1] - path[pidx + 1][1]), 2)) * 111000;
		alljourney += journey;
	}

	pathSimplifierIns.clearPathNavigators();
	//创建组件实例
	//这里构建两条简单的轨迹，仅作示例
	pathSimplifierIns.setData([{
		name: '轨迹',
		path: path
	}]);

	//创建一个巡航器
	var navg0 = pathSimplifierIns.createPathNavigator(0, //关联第1条轨迹
		{
			loop: true, //循环播放
			speed: alljourney / 10,
			pathNavigatorStyle: {
				width: 16,
				height: 32,
				content: PathSimplifier.Render.Canvas.getImageContent('{$static_dir}/assets/img/car-gray.png', onload, onerror),
				strokeStyle: null,
				fillStyle: null
			}
		});

	navg0.start();
}else{
	//轨迹回放能操作
	layer.open({
	    type: 1,
	    title:'订单轨迹回放',
	    skin: 'layui-layer-rim', //加上边框
	    area: ['70%', '70%'], //宽高
	    content: `<div class='prop_map_w' style='height:100%'>
	  				<div id='propmap' style='height:100%'></div>
	  				<div class="button-group">
					    <input type="button" class="button" value="开始动画" id="start"/>
					     <input type="button" class="button" value="暂停动画" id="pause"/>
					      <input type="button" class="button" value="继续动画" id="resume"/>
					    <input type="button" class="button" value="停止动画" id="stop"/>
					</div>
	  			</div>`,
	  	success:function(){
	  		  	var marker, lineArr = [];
			  	var propmap = new AMap.Map("propmap", {
			        resizeEnable: true,
			        center:path[0],
			        zoom: 10
			    });
			    marker = new AMap.Marker({
			        map: propmap,
			        position: path[0],
			        icon: "http://webapi.amap.com/images/car.png",
			        offset: new AMap.Pixel(-26, -13),
			        autoRotation: true
			    });
			    
			   
			
			
			
			    // 绘制轨迹
			    var polyline = new AMap.Polyline({
			        map: propmap,
			        path: path,
			        strokeColor: "#00A",  //线颜色
			        // strokeOpacity: 1,     //线透明度
			        strokeWeight: 3,      //线宽
			        // strokeStyle: "solid"  //线样式
			    });
			    var passedPolyline = new AMap.Polyline({
			        map: propmap,
			        // path: lineArr,
			        strokeColor: "#F00",  //线颜色
			        // strokeOpacity: 1,     //线透明度
			        strokeWeight: 3,      //线宽
			        // strokeStyle: "solid"  //线样式
			    });
			
			
			    marker.on('moving',function(e){
			        passedPolyline.setPath(e.passedPath);
			    })
			    map.setFitView();
			
			    AMap.event.addDomListener(document.getElementById('start'), 'click', function() {
			        marker.moveAlong(path, 1000);
			    }, false);
			     AMap.event.addDomListener(document.getElementById('pause'), 'click', function() {
			        marker.pauseMove();
			       }, false);
			      AMap.event.addDomListener(document.getElementById('resume'), 'click', function() {
			        marker.resumeMove();
			    }, false);
			    AMap.event.addDomListener(document.getElementById('stop'), 'click', function() {
			        marker.stopMove();
			    }, false);
	  	}
	});
}




}

//打开信息窗体
function openmessage(map, obj, SimpleInfoWindow, infoWindow, type) {
	var content,state,address;
	for(var index in obj) {
		for(var index1 in obj[index]) {
			if(index1 == "cont") {
				content = obj[index].cont;
			};
		};
	};
	
	
	if(type == 1) {
		if(content.work_state){
			if(content.work_state==1){
			state='在线-停止'
			}else if(content.work_state==2){
				state='在线-行驶'
			}
			else if(content.work_state==3){
				state='离线'
			}
			else if(content.work_state==4){
				state='终端没电'
			}
		}else{
			state='终端没电'
		}
		AMap.plugin('AMap.Geocoder', function() {
			geocoder = new AMap.Geocoder({
				city: "010" //城市，默认：“全国”
			});
			geocoder.getAddress(content.loc, function(status, result) {
				if(status === 'complete' && result.info === 'OK') {
					//获得了有效的地址信息:
					address= result.regeocode.formattedAddress;
					infoWindow = new SimpleInfoWindow({
						infoTitle: '<strong>' + "车辆信息"+'</strong>',
						infoBody: `<div><div>车牌号:${content.num}</div><div>所在地址:${address}</div><div>状态:${state}</div></div>`,
						offset: new AMap.Pixel(0, -31)
					});
					infoWindow.open(map, obj.getPosition());
				} else {
					address="获取地址失败";

					infoWindow = new SimpleInfoWindow({
						infoTitle: '<strong>' + "车辆信息"+'</strong>',
						infoBody: `<div><div>车牌号:${content.num}</div><div>所在地址:${address}</div><div>状态:${state}</div></div>`,
						offset: new AMap.Pixel(0, -31)
					});
					infoWindow.open(map, obj.getPosition());
				}
			});
			
		})
		
	} else {
		infoWindow = new SimpleInfoWindow({
			infoTitle: '<strong>' + content.drivername + '</strong>',
			infoBody: `<div><div>司机姓名:${content.drivername}</div><div>出发地:${content.begin}</div><div>目的地:${content.end}</div><div>订单花费:${content.money}</div></div>`,
			offset: new AMap.Pixel(0, -31)
		});
		infoWindow.open(map, obj.getPosition());
	}
	
}
//关闭信息窗体
function closemessage(map, obj, SimpleInfoWindow, infoWindow){
	infoWindow = new SimpleInfoWindow({
			infoTitle: '<strong></strong>',
			infoBody: `<div></div>`,
			offset: new AMap.Pixel(0, -31)
		});
		infoWindow.open(map, obj.getPosition());
		infoWindow.close()
}
//点聚合
function addCluster(tag,origin,cluster, markers) {
    	
    	markers=[]
    	var _renderCluserMarker = function (context) {
	        var factor = Math.pow(context.count/count,1/18)
	        var div = document.createElement('div');
	        var Hue = 180 - factor* 180;
	        var bgColor = 'hsla('+Hue+',100%,50%,0.7)';
	        var fontColor = 'hsla('+Hue+',100%,20%,1)';
	        var borderColor = 'hsla('+Hue+',100%,40%,1)';
	        var shadowColor = 'hsla('+Hue+',100%,50%,1)';
	        div.style.backgroundColor = bgColor
	        var size = Math.round(30 + Math.pow(context.count/count,1/5) * 20);
	        div.style.width = div.style.height = size+'px';
	        div.style.border = 'solid 1px '+ borderColor;
	        div.style.borderRadius = size/2 + 'px';
	        div.style.boxShadow = '0 0 1px '+ shadowColor;
	        div.innerHTML = context.count;
	        div.style.lineHeight = size+'px';
	        div.style.color = fontColor;
	        div.style.fontSize = '14px';
	        div.style.textAlign = 'center';
	        context.marker.setOffset(new AMap.Pixel(-size/2,-size/2));
	        context.marker.setContent(div)
	     }
    	for(var maidx=0;maidx<origin.car.length;maidx++){
    		if(origin.car[maidx].point){
    			markers.push(origin.car[maidx].point)
    		}
    	}
    	var count  = markers.length;
        if (cluster) {
            cluster.setMap(null);
        }
        if (tag == 2) { //完全自定义
            cluster = new AMap.MarkerClusterer(map,markers,{
                gridSize:30,
                renderCluserMarker:_renderCluserMarker,
                maxZoom:17

            });
        } else if (tag == 1) { //自定义图标
            var sts = [{
                url: "http://a.amap.com/jsapi_demos/static/images/blue.png",
                size: new AMap.Size(32, 32),
                offset: new AMap.Pixel(-16, -16)
            }, {
                url: "http://a.amap.com/jsapi_demos/static/images/green.png",
                size: new AMap.Size(32, 32),
                offset: new AMap.Pixel(-16, -16)
            }, {
                url: "http://a.amap.com/jsapi_demos/static/images/orange.png",
                size: new AMap.Size(36, 36),
                offset: new AMap.Pixel(-18, -18)
            },{
                url: "http://a.amap.com/jsapi_demos/static/images/red.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24)
            },{
                url: "http://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24)
            }];
            cluster = new AMap.MarkerClusterer(map, markers, {
                styles: sts,
                gridSize:30,
                maxZoom:17
            });
        } else { //默认样式
            cluster = new AMap.MarkerClusterer(map, markers,{gridSize:30,maxZoom:17});

        }
        return cluster
    }
	
});
